package com.itheima.health.security;

import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Slf4j
public class CjxPassWordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {

        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        //String password=null;
        if (rawPassword.length()==0 || null ==rawPassword){
            throw new BusinessRuntimeException("输入数据有误");
        }
        if (encodedPassword.length()==0 || null ==encodedPassword){
            throw new BusinessRuntimeException("数据有误");
        }
        if (encodedPassword.subSequence(0,4).equals("md5_")){
            return ("md5_"+MD5Util.encode(rawPassword.toString().substring(4))).equals(encodedPassword);
        }
        if (encodedPassword.subSequence(0,8).equals("{bcrypt}")){
            //log.info("==={}",new BCryptPasswordEncoder().matches(rawPassword,encodedPassword.substring(8)));
            return new BCryptPasswordEncoder().matches(rawPassword,encodedPassword.substring(8));
           // return ("{bcrypt}"+new BCryptPasswordEncoder().encode(rawPassword.toString().substring(8))).matches(encodedPassword);
        }
        if (MD5Util.encode(rawPassword.toString()).equals(encodedPassword)){
            return true;
        }else if (new BCryptPasswordEncoder().matches(rawPassword,encodedPassword)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        CjxPassWordEncoder cjxPassWordEncoder = new CjxPassWordEncoder();
        cjxPassWordEncoder.encode("md5_12222");
    }
}
